package test.study.mq.kafka.consumer;

import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.header.Headers;
import org.apache.kafka.common.serialization.StringDeserializer;

import java.time.Duration;
import java.util.Arrays;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicBoolean;

@Slf4j
public class Consumer_01_Main {

    private static AtomicBoolean RUNNING = new AtomicBoolean(true);

    private static String servers = "150.158.122.249:9092";

    public static void main(String[] args) {
        //
        Properties props = new Properties();
        props.put("bootstrap.servers", servers);
        props.put("key.deserializer", StringDeserializer.class);
        props.put("value.deserializer", StringDeserializer.class);
        props.put("group.id", "test");
        //
        props.put("enable.auto.commit", "true");
        props.put("auto.commit.interval.ms", "1000");

        //Step-1: 创建消费者
        KafkaConsumer<String, String> consumer = new KafkaConsumer(props);
        //Step-2: 订阅主题
        consumer.subscribe(Arrays.asList("topic-3"));
        //Step-3: 拉取数据
        while (RUNNING.get()) {
            ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(1 * 1000));
            for (ConsumerRecord<String, String> record : records) {
                Headers headers = record.headers();
                if (headers != null) {
                    headers.forEach(e -> {
                        log.info("{}= {}", e.key(), new String(e.value()));
                    });
                }
                log.info("partition= {}, _2_offset= {}, value= {}, key= {}",
                        record.partition(), record.offset(), record.value(), record.key());
            }
        }
        //Step-4: 关闭

    }
}
